﻿package net.wangit.jdbc.database;

import net.wangit.jdbc.JDBCException;

public class PostgreSQL extends Database {

	public PostgreSQL() {
		registerType(1, 1, "CHAR($p)");
		registerType(2, 12, "VARCHAR($p)");
		registerType(11, 5, "INT2");
		registerType(12, 4, "INT4");
		registerType(13, -5, "INT8");
		registerType(21, 6, "FLOAT4");
		registerType(22, 8, "FLOAT8");
		registerType(23, 2, "NUMERIC");
		registerType(31, 91, "DATE");
		registerType(32, 92, "TIME");
		registerType(33, 93, "TIMESTAMP");
		registerType(41, 2005, "TEXT");
		registerType(43, 2004, "BYTEA");
	}

	public int getTypeCode(int sqlTypeCode, String columnTypeName,
			int precision, int scale) throws JDBCException {
		switch (sqlTypeCode) {
		case 1: // '\001'
			return 1;

		case 12: // '\f'
			return 2;

		case 5: // '\005'
			return 11;

		case 4: // '\004'
			return 12;

		case -5:
			return 13;

		case 6: // '\006'
			return 21;

		case 8: // '\b'
			return 22;

		case 2: // '\002'
			return 23;

		case 91: // '['
			return 31;

		case 92: // '\\'
			return 32;

		case 93: // ']'
			return 33;

		case 2005:
			return 41;

		case -2:
		case 2004:
			return 43;
		}
		throw new JDBCException((new StringBuilder(
				"Unsupported sqlType: sqlTypeCode=")).append(sqlTypeCode)
				.append(",columnTypeName=").append(columnTypeName).toString());
	}

	public int getDefaultBatchSize() {
		return 15;
	}

	public String getAddColumnString() {
		return "add column";
	}

	public String getSequenceNextValString(String sequenceName) {
		return (new StringBuilder("select nextval ('")).append(sequenceName)
				.append("')").toString();
	}

	public String getCreateSequenceString(String sequenceName) {
		return (new StringBuilder("create sequence ")).append(sequenceName)
				.toString();
	}

	public String getDropSequenceString(String sequenceName) {
		return (new StringBuilder("drop sequence ")).append(sequenceName)
				.toString();
	}

	public String getCascadeConstraintsString() {
		return "";
	}

	public boolean supportsSequences() {
		return true;
	}

	public boolean supportsLimit() {
		return true;
	}

	public String getLimitString(String sql, boolean hasOffset) {
		return (new StringBuffer(sql.length() + 20)).append(sql).append(
				hasOffset ? " limit ? offset ?" : " limit ?").toString();
	}

	public boolean bindLimitParametersInReverseOrder() {
		return true;
	}

	public boolean supportsForUpdateOf() {
		return true;
	}
}
